﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Threading;

namespace SMSTester.Controls
{
    public partial class SendMail : UserControl
    {
        public string TableName = string.Empty;
        public string TableNameBody = string.Empty;

        public void Init(bool paramVisible)
        {
            this.Visible = paramVisible;
            if (paramVisible)
            {
                this.Dock = DockStyle.Fill;
            }
        }

        public SendMail()
        {
            InitializeComponent();
        }

        public const string cApplicationRegistryPath = "HKEY_CURRENT_USER\\Software\\SMSTester";
        public void GetParams()
        {
            int i;
            try
            {
                if (Int32.TryParse(
                       Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "ThreadCount",
                           seThreadCount.Value
                           ).ToString(), out i))
                    seThreadCount.Value = i;

                txtHost.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "Host",
                           txtHost.Text
                           ).ToString();

                txtPort.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "Port",
                           txtPort.Text
                           ).ToString();

                txtSMTPUser.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "SMTPUser",
                           txtSMTPUser.Text
                           ).ToString();

                txtSMTPPassword.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "SMTPPassword",
                           txtSMTPPassword.Text
                           ).ToString();

                txtUser.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "User",
                           txtUser.Text
                           ).ToString();

                txtPassword.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "Password",
                           txtPassword.Text
                           ).ToString();
            }
            catch { }
        }

        public void SetParams()
        {
            Microsoft.Win32.Registry.SetValue(
                cApplicationRegistryPath,
                this.Name + "ThreadCount",
                Convert.ToInt32(seThreadCount.Value).ToString()
                );

            Microsoft.Win32.Registry.SetValue(
                          cApplicationRegistryPath,
                          this.Name + "Host",
                          txtHost.Text
                          );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "Port",
                       txtPort.Text
                       );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "SMTPUser",
                       txtSMTPUser.Text
                       );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "SMTPPassword",
                       txtSMTPPassword.Text
                       );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "User",
                       txtUser.Text
                       );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "Password",
                       txtPassword.Text
                       );
        }

        int MessageIndex = -1;
        DataTable MessageTable = null;

        private void btnSend_Click(object sender, EventArgs e)
        {
            using (new CursorWait())
            {
                MessageIndex = -1;
                MessageTable = SQLConnect.Instance.Select(
                    @"
select  
	body.BodyID
	,mess.MessageID
	,body.Body as Body
	,body.IsUnicode as IsUnicode
	,body.Subject as Subject
	,mess.Sender as Sender
	,mess.Recipient as Recipient
  FROM " + TableNameBody + @" body
	left join " + TableName + @" mess on mess.BodyID = body.BodyID
                    ",
                    new List<KeyValuePair<string, Type>>()
                    {
	                    { new KeyValuePair<string,Type>("BodyID", typeof(int))},
	                    { new KeyValuePair<string,Type>("Body", typeof(string))},
	                    { new KeyValuePair<string,Type>("IsUnicode", typeof(bool))},
	                    { new KeyValuePair<string,Type>("Subject", typeof(string))},
	                    { new KeyValuePair<string,Type>("MessageID", typeof(int))},
	                    { new KeyValuePair<string,Type>("Sender", typeof(string))},
	                    { new KeyValuePair<string,Type>("Recipient", typeof(string))},
                    }
                    );

                progressBar.Visible = true;
                progressBar.Properties.Minimum = 0;
                progressBar.Properties.Maximum = MessageTable.Rows.Count;
                progressBar.Position = 0;
                txtLog.Text = "";

                thrPort = txtPort.Text.Trim();
                thrHost = txtHost.Text.Trim();
                thrSMTPUser = txtSMTPUser.Text.Trim();
                thrSMTPPassword = txtSMTPPassword.Text.Trim();
                thrUser = txtUser.Text.Trim();
                thrPassword = txtPassword.Text.Trim();
                thrSaveToBase = chbSaveToBase.Checked;

                // Create and run threads
                List<System.Threading.Thread> locThreads = new List<System.Threading.Thread>();
                for (int i = 0; i < seThreadCount.Value; i++)
                {
                    System.Threading.Thread locThread = new System.Threading.Thread(RunThread);
                    locThread.Name = "Thread #" + i.ToString();
                    locThread.Priority = System.Threading.ThreadPriority.Lowest;
                    locThread.Start();
                    locThreads.Add(locThread);
                }

                // wait threads
                while (MessageIndex < MessageTable.Rows.Count-1)
                {
                    System.Threading.Thread.Sleep(1000);
                    if (MessageIndex < progressBar.Properties.Maximum - 1)
                        progressBar.Position = MessageIndex;
                    progressBar.Refresh();
                }
                progressBar.Visible = false;

            }
        }

        private string thrPort;
        private string thrHost;
        private string thrSMTPUser;
        private string thrSMTPPassword;
        private string thrUser;
        private string thrPassword;
        private bool thrSaveToBase;
        private void RunThread()
        {
            while (true)
            {

                DataRow dr = null;

                Monitor.Enter(this);
                if (MessageIndex < MessageTable.Rows.Count - 1)
                {
                    MessageIndex++;
                    dr = MessageTable.Rows[MessageIndex];
                }
                Monitor.Exit(this);

                if (dr != null)
                {
                    Thread.Sleep(10);

                    // send email

                    SmtpClient smtp = new SmtpClient();
                    smtp.Credentials = new System.Net.NetworkCredential(thrSMTPUser, thrSMTPPassword);
                    smtp.Port = Convert.ToInt32(thrPort);
                    smtp.Host = thrHost;
                    smtp.EnableSsl = false;
                    MailMessage mail = new MailMessage();

                    mail.From = new MailAddress(Convert.ToString(dr["Sender"]).Trim());
                    mail.To.Add(Convert.ToString(dr["Recipient"]).Replace(".mail", "@mail").Trim());
                    //mail.To.Add("shurik@mail.zp.ua");
                    mail.Subject = Convert.ToString(dr["Subject"]).Trim() +
                        System.Threading.Thread.CurrentThread.Name
                        ;


                    string locBody = Convert.ToString(dr["Body"]).Trim();
                    mail.Body = locBody;
                    mail.BodyEncoding = Encoding.Default;
                    mail.IsBodyHtml = false;
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
                    mail.Headers.Add("BodyId", Convert.ToString(dr["BodyId"]).Trim());
                    mail.Headers.Add("MessageId", Convert.ToString(dr["MessageId"]).Trim());
                    if (thrSaveToBase)
                        mail.Headers.Add("Base", "1");
                    else
                        mail.Headers.Add("Base", "0");
                    mail.ReplyTo = new MailAddress(Convert.ToString(dr["Sender"]).Trim());

                    try
                    {
                        smtp.Send(mail);
                    }
                    catch(Exception exc)
                    {
                        txtLog.Text += "\r\n" + exc.Message;
                    }
                    

                }
                else
                    break;
            }
        }

    }
}
